package cn.wujiangbo.service.system.impl;

import cn.wujiangbo.exception.MyException;
import cn.wujiangbo.service.system.FileService;
import cn.wujiangbo.util.DateUtils;
import cn.wujiangbo.vo.UploadFileVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.Date;

/**
 * <p>文件上传-保存到服务器本地磁盘</p>
 *
 * @Author 波波老师(weixin:javabobo0513)
 */
@Service
@Slf4j
public class FileServiceLocalImpl implements FileService {

    @Value("${server.port}")
    private String port;

    @Override
    public UploadFileVo uploadFile(MultipartFile file, String folderName) {
        if (file.isEmpty()) {
            throw new MyException("上传文件不能为空！");
        }
        UploadFileVo vo = new UploadFileVo();
        try {
            String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) {
                path = new File("");
            }
            String localPath = "/UploadFiles/" + DateUtils.getCurrentYearMonth() + "/" + folderName + "/";
            File upload = new File(path.getAbsolutePath(), localPath);
            if (!upload.exists()) {
                upload.mkdirs();
            }
            String fileName = new Date().getTime() + "." + fileExt;
            File dest = new File(upload.getAbsolutePath() + "/" + fileName);
            file.transferTo(dest);
            //如果使用idea或者eclipse重启项目，发现之前上传的图片或者文件丢失，将下面一行代码注释打开
            FileUtils.copyFile(dest, new File("E:\\workspace\\EasyJavaTemplateMaster\\EasyJavaTemplate\\SpringBoot\\src\\main\\resources\\static\\UploadFiles" + "/" + DateUtils.getCurrentYearMonth() + "/" + folderName + "/" + fileName));
            //封装返回数据
            vo.setFileName(fileName);
            vo.setFileSize(file.getSize());
            vo.setFileFullPath("http://localhost:" + port + "/static/UploadFiles/" + DateUtils.getCurrentYearMonth() + "/" + folderName + "/" + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException("上传文件到本地磁盘异常：" + e.getMessage());
        }
        return vo;
    }
}
